package com.common.utils;

import com.common.result.JsonResult;
import com.common.result.ResultEnum;
import jdk.jfr.internal.tool.Main;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.Objects;

import static org.springframework.util.Assert.notNull;
@Slf4j
@Component
public class FileUploadUtils {
    public static void main(String[] args) {
//        String time = LocalDateTime.now().toString();
//        //14
//        StringBuilder stringBuilder = new StringBuilder(time);
//        stringBuilder.replace(13, 14, "-");
//        stringBuilder.replace(16, 17, "-");
//        stringBuilder.append("-");
//
//        String initialFileName = "111hahahhahah";
//        stringBuilder.append(initialFileName);
////        System.out.println(stringBuilder.toString());
//        String oldName="aaaaa.pdf";
//        String s = makeFileName(oldName);
//        System.out.println(s);
//        LocalDateTime localDateTime=LocalDateTime.now();
//        System.out.println(localDateTime);
        makeFileName(114514);

    }

    public static final long MAX_SIZE = 50 * 1024 * 1024L;


    @Value("${config.base_path}")
    private  String BASE_PATH;

////    @Value("${config.picture_path}")

    private  String PICTURE_PATH="";

    /*
    * @param file 要下载到文件里的数据
    * @param path 下载的完整路径
    * @Param uid 用户id
     */
    public int editorUpload(String file,String uploadPath,long uid) {
        log.info("fileUploadUtiles打印base_path:{}",BASE_PATH);
        log.info("fileUploadUtils打印uploadPath:{}",uploadPath);
        if (file==null){
            log.error("file不能为空");
            return 1;
        }


        File file1=new File(uploadPath);
        try {
            file1.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        BufferedWriter wtiter=null;
        File file2=new File("D:\\baking\\article");
        boolean exists = file2.exists();
        log.info("fileUploadUtils:文件夹是否存在:{}",exists);
        try {
            if(file1.exists()){
                log.info("fileUploadUtils:file已存在");
                Files.write(
                        Paths.get(uploadPath),  // 路径转 Path 对象
                        file.getBytes(StandardCharsets.UTF_8),  // String 转字节数组（指定编码）
                        java.nio.file.StandardOpenOption.CREATE,  // 不存在则创建文件
                        java.nio.file.StandardOpenOption.TRUNCATE_EXISTING  // 存在则覆盖（默认）

                );
                return 0;

//                BufferedWriter writer = new BufferedWriter(
//                        new OutputStreamWriter(
//                                new FileOutputStream(file, false),
//                                StandardCharsets.UTF_8
//                        )
//                );
//                writer.write(file);

            }else {
                log.info("fileUploadUtils:file不存在");
                return 2;//创建失败
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("utils写入文章失败");
            return 2;
        }finally {
            if (wtiter!=null){
                try {
                    wtiter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }




    }




    public  int upload(MultipartFile file, String path) throws IOException {
        if (file==null){
            log.info("fileUploadUtils:file是null");
            return 3;
        }
        if (file.isEmpty()) {
            return 3;
            // TODO: 2025/6/29 文件不能为空
        }



        if (file.getOriginalFilename().length() > 1000) {
            // TODO: 2025/6/29 抛出异常，文件名称过大
        }

        long size = Objects.requireNonNull(file.getSize());
        if (size > MAX_SIZE) {
            // TODO: 2025/6/29 文件太大
        }

        String newFileName = makeFileName(file.getOriginalFilename());
        Path path1 = Paths.get(BASE_PATH);
        Path path2 = path1.resolve(path);
        Path targetPath = path2.resolve(newFileName);

        file.transferTo(targetPath);
        return 0;

    }
//    public static void upload(MultipartFile file) throws IOException {
//        if (file.getOriginalFilename().length() > 1000) {
//            // TODO: 2025/6/29 抛出异常，文件名称过大
//        }
//        if (file.isEmpty()) {
//            // TODO: 2025/6/29 文件不能为空
//        }
//        long size = Objects.requireNonNull(file.getSize());
//        if (size > MAX_SIZE) {
//            // TODO: 2025/6/29 文件太大
//        }
//
//        String newFileName = makeFileName(file.getOriginalFilename());
//        Path targetPath = Paths.get(newFileName);
//        file.transferTo(targetPath);
//
//    }

    public int uoloadPicture(MultipartFile file)throws IOException{
        String fileName = file.getName();
        Path path = Paths.get(fileName);
        if (path.endsWith(".jpg")|| path.endsWith(".png")||path.endsWith(".gif")){
            upload(file,PICTURE_PATH);
        }
        else{
            return 1;
        }
        return 0;
    }

    public int uoloadPicture(MultipartFile file,long uid,String uploadPath){
        String fileName = file.getName();
        Path path = Paths.get(fileName);
        if (path.endsWith(".jpg")|| path.endsWith(".png")||path.endsWith(".gif")){
            String fileName1 = makeFileName(uid);
            InputStream inputStream = null;
            try {
                inputStream = file.getInputStream();
                OutputStream outputStream=new FileOutputStream(uploadPath);
                int copy = FileCopyUtils.copy(inputStream, outputStream);
                return 0;
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        else{
            return 1;
        }
        return 0;
    }


    public static String makeFileName(String oldFileName) {
        String time = LocalDateTime.now().toString();
        StringBuilder stringBuilder = new StringBuilder(time);
        stringBuilder.replace(10, 11, "\\");
        stringBuilder.replace(13, 14, "-");
        stringBuilder.replace(16, 17, "-");
//        stringBuilder.replace(19, 20, "-");
        stringBuilder.append("\\");
        stringBuilder.append(oldFileName);
        return stringBuilder.toString();
    }
    public static String makeFileName(long uid) {
        String time = LocalDateTime.now().toString();
        StringBuilder stringBuilder = new StringBuilder(time);
        stringBuilder.replace(10, 11, "_");
        stringBuilder.replace(13, 14, "-");
        stringBuilder.replace(16, 17, "-");
        stringBuilder.append("_"+uid);
        return stringBuilder.toString();
    }




//    public static void main(String[] args) {
//        String s = makeFileName("11111.aaa");
//        System.out.println(s);
//    }
}
